package com.dongbing.support.handler;

import com.alibaba.fastjson2.JSONObject;
import com.dongbing.entity.support.BatchTaskDetailPO;
import com.dongbing.entity.support.BatchTaskPO;
import com.dongbing.enums.BatchTaskState;
import com.dongbing.support.service.BatchTaskDetailService;
import com.dongbing.support.service.BatchTaskService;
import com.dongbing.support.strategy.BatchTaskExecutorStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class BatchTaskExecuteHandler {

    private final BatchTaskService batchTaskService;

    private final BatchTaskDetailService batchTaskDetailService;

    public void execute(String message) {
        log.info("[批次任务提交]收到批次任务执行消息:{}", message);
        JSONObject msgBody = JSONObject.parseObject(message);
        BatchTaskPO taskData = msgBody.getObject("task", BatchTaskPO.class);
        if (Objects.isNull(taskData)) {
            log.error("[批量任务]消息中无任务信息");
            return;
        }
        BatchTaskPO taskPO = batchTaskService.getById(taskData.getId());
        if (Objects.isNull(taskPO)) {
            log.error("[批量任务]批量任务不存在");
            return;
        }
        if (BatchTaskState.DONE.equals(taskPO.getState()) || BatchTaskState.ERROR.equals(taskPO.getState())) {
            log.error("[批量任务]批量任务已完成,任务ID:{}", taskPO.getId());
            return;
        }

        List<BatchTaskDetailPO> details = BatchTaskExecutorStrategy.doExecute(taskPO, msgBody);
    }

}
